package com.cl.code.database.mybatis.module.result;

import com.cl.code.database.mybatis.module.page.PageResult;
import com.github.pagehelper.PageInfo;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author chengliang
 * @since 1.0.0
 */
public class PageResultWrapper<Entity> {

    private final List<Entity> list;

    public PageResultWrapper(List<Entity> list) {
        this.list = list;
    }

    public static <Entity> PageResultWrapper<Entity> of(List<Entity> list) {
        return new PageResultWrapper<>(list);
    }

    public PageResult<Entity> result() {
        return PageResult.build(this.list);
    }

    public <R> PageResult<R> result(Function<Entity, R> function) {
        if (CollectionUtils.isEmpty(this.list)) {
            return PageResult.empty();
        } else {
            List<R> list = this.list.stream().map(function).collect(Collectors.toList());
            return PageResult.build(PageInfo.of(this.list).getTotal(), list);
        }
    }

    public <R> PageResult<R> resultBatch(Function<List<Entity>, List<R>> function) {
        if (CollectionUtils.isEmpty(this.list)) {
            return PageResult.empty();
        } else {
            List<R> list = function.apply(this.list);
            return PageResult.build(PageInfo.of(this.list).getTotal(), list);
        }
    }

}
